<template>
  <div class="m-header-avatar">
    <div class="avatar" @click="avatarUpload">
      <img :src="defaultUrl" class="avatar" />
      <el-icon class="icon-upload">
        <Plus />
      </el-icon>
    </div>
    <el-dialog v-model="dialogVisible" top="30px" width="700px">
      <template #title>
        <span class="el-dialog__title">头像上传</span>
      </template>
      <div class="upload-dialog">
        <div class="slide-a">
          <div class="avatar-cropper">
            <AvatarCropper :avatarUrl="avatarUrl" @change="realTime" ref="avatar" />
          </div>
          <div style="display: flex; justify-content: center; margin-top: 10px">
            <el-upload
              :action="uploadAvatar"
              multiple
              :headers="header"
              :before-upload="beforeUploadAction"
              :on-success="handleOnSuccess"
              accept="image/*"
            >
              <el-button type="primary"
                >点击上传图片
                <el-icon>
                  <Upload />
                </el-icon>
              </el-button>
            </el-upload>
          </div>
        </div>
        <div class="slide-b">
          <div class="preview-wrap" :style="previewStyle">
            <img :src="previewsOption.url" class="uploadImg" :style="previewsOption.img" />
          </div>

          <div class="preview-wrap" :style="previewStyle1">
            <img :src="previewsOption.url" class="uploadImg" :style="previewsOption.img" />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="success" @click="configUpload"> 提交 </el-button>
          <el-button type="warning" @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import AvatarCropper from '@/components/AvatarCropper/index.vue'
  import { ElMessage, UploadFile, UploadFiles } from 'element-plus'
  import { reqUserProfileAvatar, USER_API } from '@/api/user'
  import { useUserStore } from '@/store/modules/user'

  const UserStore = useUserStore()
  // 上传图片路径
  let uploadAvatar = import.meta.env.VITE_APP_BASE_API + USER_API.USER_AVATAR_URL
  let defaultUrl = import.meta.env.VITE_APP_BASE_API + UserStore.userInfo.avatar
  let avatarUrl = import.meta.env.VITE_APP_BASE_API + UserStore.userInfo.avatar
  let dialogVisible = ref<boolean>(false)
  let avatar = ref()
  let previewsOption = ref({})
  let previewStyle = ref({})
  let previewStyle1 = ref({})

  // 请求头设置
  const header = ref({
    Authorization: UserStore.token,
  })

  const avatarUpload = () => {
    dialogVisible.value = true
  }

  const props = defineProps({
    userInfo: {
      type: Object,
      required: true,
    },
  })

  const beforeUploadAction = (file, fileLi) => {
    return new Promise((resolve, reject) => {
      let reader = new FileReader()
      let reg = /\.jpg$|\.jpeg$|\.gif$|\.png$/i
      reader.readAsDataURL(file)
      let name = file.name
      if (reg.test(name)) {
        reader.onload = (e: ProgressEvent<FileReader>) => {
          //avatarUrl = e.target.result as string;
          resolve(e.target.result)
        }
      } else {
        ElMessage.error('请上传图片')
        reject()
      }
    })
  }

  // 上传成功的函数
  const handleOnSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log('文件上传成功')
    avatarUrl = import.meta.env.VITE_APP_BASE_API + response.imgUrl
    console.log(response)
    console.log(uploadFile)
    console.log(uploadFiles)
  }

  // 裁剪之后上传
  const configUpload = async () => {
    defaultUrl = await avatar.value.getBase64()
    // 进行上传
    let base64Url = await avatar.value.getBase64()
    // 根式转换
    let file = await base64ImgtoFile(base64Url)
    // 构建表单
    /*将file进行上传*/
    const form = new FormData()
    form.set('file', file)
    // 进行上传啊
    await reqUserProfileAvatar(form)
      .then((req: any) => {
        if (req.code === 200) {
          ElMessage.success('裁剪成功')
          UserStore.userInfo.avatar = req.imgUrl
        } else {
          ElMessage.success('裁剪失败,请重试!')
        }
      })
      .catch(() => {})
    dialogVisible.value = false
  }

  const realTime = (data) => {
    previewsOption.value = data
    let options = {
      width: data.w + 'px',
      height: data.h + 'px',
      overflow: 'hidden',
    }
    previewStyle.value = {
      ...options,
      zoom: 200 / data.w,
    }
    previewStyle1.value = {
      ...options,
      zoom: 120 / data.w,
    }
  }

  const base64ImgtoFile = (dataurl, filename = 'file') => {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime,
    })
  }
</script>

<style lang="scss" scoped>
  .el-dialog__title {
    font-weight: bold;
  }

  .m-header-avatar {
    width: 100%;

    .avatar {
      border-radius: 50%;
      border: 1px solid black;
      width: 160px;
      height: 160px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    .icon-upload {
      color: white;
      font-size: 60px;
      position: absolute;
      display: none;
    }

    .avatar:hover {
      .icon-upload {
        display: block;
      }
    }

    .avatar-cropper {
      width: 400px;
      height: 400px;
    }

    .upload-dialog {
      display: flex;
      justify-content: space-between;
    }

    .preview-wrap {
      width: 160px;
      height: 160px;
      overflow: hidden;
      border-radius: 50%;
      margin-bottom: 40px;
    }

    .slide-b {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
</style>
